package com.lean.android.ad.core.interstitial

import android.app.Activity
import androidx.annotation.RestrictTo
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import com.lean.android.ad.core.AdLoadState
import com.lean.android.ad.core.AdLoader
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.core.ErrorCode
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.ReportHelper.toCpmInt
import com.lean.android.ad.utils.AdLog
import java.util.UUID
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

@RestrictTo(RestrictTo.Scope.LIBRARY)
class InterstitialAdLoader(private val fullAd: Boolean) : AdLoader {

    companion object {
        private fun getAdSlotInterstitial(fullAd: Boolean): AdSlot {
            return AdSlot.Builder()
                .setCodeId(AdSdk.getAdConfig().adParamsProvider.getInterstitialAdId())
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)//设置横竖屏方向
                .setMediationAdSlot(
                    MediationAdSlot.Builder().setMuted(false).setVolume(1f).setBidNotify(true)
                        .build()
                ).build()
        }
    }

    override suspend fun load(activity: Activity): AdLoadState {
        val requestId = UUID.randomUUID().toString()
        val logTag = if (fullAd) AdLog.AdFullLoadTag else AdLog.AdInsertLoadTag
        AdLog.d(logTag, "start to load interstitialAd , requestId $requestId.")
        return suspendCoroutine { coroutine ->
            val nativeLoader = TTAdSdk.getAdManager().createAdNative(activity)
            nativeLoader.loadFullScreenVideoAd(
                getAdSlotInterstitial(fullAd),
                object : TTAdNative.FullScreenVideoAdListener {
                    override fun onError(code: Int, message: String?) {
                        AdLog.e(
                            logTag,
                            "interstitialAd load failed, requestId $requestId, code $code, message $message"
                        )
                        ReportHelper.reportAdEvent(
                            requestId = requestId,
                            eventType = ReportHelper.AdEventType.AdError,
                            adPosition = if (fullAd) ReportHelper.AdPositionType.Full else ReportHelper.AdPositionType.Interstitial,
                            errorCode = code.toString()
                        )

                        coroutine.resume(AdLoadState.Error(ErrorCode.ErrorAdLoadFailed, message))
                    }

                    override fun onFullScreenVideoAdLoad(ad: TTFullScreenVideoAd) {
                        AdLog.d(
                            logTag, "interstitialAd onFullScreenVideoAdLoad, requestId $requestId"
                        )
                    }

                    override fun onFullScreenVideoCached() {

                    }

                    override fun onFullScreenVideoCached(ad: TTFullScreenVideoAd) {
                        AdLog.d(
                            logTag,
                            "interstitialAd onFullScreenVideoCached, load success. requestId $requestId"
                        )
                        ad.mediationManager?.bestEcpm?.also { cpmInfo ->
                            val cpm = cpmInfo.ecpm.toCpmInt()
                            ReportHelper.reportAdEvent(
                                requestId = requestId,
                                eventType = ReportHelper.AdEventType.AdLoaded,
                                platformId = cpmInfo.sdkName.orEmpty(),
                                adPosition = if (fullAd) ReportHelper.AdPositionType.Full else ReportHelper.AdPositionType.Interstitial,
                                cpm = cpm
                            )
                        }

                        coroutine.resume(AdLoadState.Success(InterstitialAd(ad, fullAd, requestId)))
                    }
                })
        }
    }
}